package com.glamour.hlcity.module.spider.util;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;

import com.glamour.hlcity.common.data.model.UrlSearchObj;
import com.glamour.hlcity.common.util.ListUtil;
import com.glamour.hlcity.common.util.StringUtil;

/**
 * URL操作工具类
 * 
 * @author zhaoxing.liuzx
 * 
 */
public class UrlUtil {

	public final static String QUESTION_MARK = "[?]";
	public final static String AND_MARK = "&";
	public final static String EQUAL_MARK = "=";
	/**
	 * 绝对不能存在url中参数key为下面的这种情况
	 */
	public final static String HLCITY_URL_ANALYSIS_KEY="@HLCITY_URL_ANALYSIS_KEY@";

	/**
	 * 将url最后端的字符串以"?","&"和"="进行拆分，组装成一个map（具体请看其实现）
	 * 
	 * @param urlPart
	 *            url最后端的字符串
	 * @return
	 */
	public static Map<String, Object> url2Map(String urlPart) {

		Map<String, Object> map = new HashMap<String, Object>();
		// 如果为空，返回空map
		if (StringUtils.isBlank(urlPart)) {
			return map;
		}
		List<String> partList=StringUtil.split(urlPart, QUESTION_MARK);
		//没有参数
		if(partList.size()==1){
			map.put(HLCITY_URL_ANALYSIS_KEY, ListUtil.first(partList));
			return map;
		}
		map.put(HLCITY_URL_ANALYSIS_KEY, ListUtil.first(partList));
		List<String> params=StringUtil.split(partList.get(1), AND_MARK);
		List<String> singer;
		for(String param:params){
			singer=StringUtil.split(param, EQUAL_MARK);
			if(singer.size()>1){
				map.put(singer.get(0), singer.get(1));
			}else if(singer.size()==1){
				map.put(singer.get(0), "");
			}
		}
		return map;
	}
	
	public static UrlSearchObj execute(String urlPart){
		Map<String,Object> map=url2Map(urlPart);
		return null;
	}
	
	public static void main(String[] args){
		Map<String, Object> map=url2Map("index.jsp?a=a&b");
		System.out.println(map.toString());
	}
}
